package org.springframework.web.servlet.view.json;

import com.alibaba.fastjson.support.spring.FastJsonJsonView;
import com.monkey.core.web.ServletRequestContextHolder;
import com.monkey.core.web.response.MonkeyResponseDto;
import com.monkey.utils.MonkeyUtils;

import javax.servlet.ServletRequest;
import java.util.Map;

/**
 * Created by 1 on 2016/4/19.
 */
public class MonkeyFastJsonView extends FastJsonJsonView {
    public static final String DATA_KEY = "JSON_DATA";
    private boolean extractValueFromSingleKeyModel = false;

    @Override
    @SuppressWarnings("unchecked")
    protected Object filterModel(Map<String, Object> model) {
        ServletRequest request = ServletRequestContextHolder.getRequest();
        if (MonkeyUtils.isNotEmpty(request)) {
            Object data = request.getAttribute(DATA_KEY);
            if (data != null && data instanceof MonkeyResponseDto) {
                return data;
            }
        }
        Map<String, Object> result = (Map<String, Object>) super.filterModel(model);
        return (this.extractValueFromSingleKeyModel && result.size() == 1 ? result.values().iterator().next() : result);
    }

    public boolean isExtractValueFromSingleKeyModel() {
        return extractValueFromSingleKeyModel;
    }

    public void setExtractValueFromSingleKeyModel(boolean extractValueFromSingleKeyModel) {
        this.extractValueFromSingleKeyModel = extractValueFromSingleKeyModel;
    }
}
